<template>
  <div class="amap-page-container">
    <el-amap ref="map"
      class="amap-demo"
      :center="center"
      :zoom="zoom"
      :map-style="defaultMap"
      view-mode="3D"
      @init="init"
      @mousewheel="changeZoom">
      <!-- 卫星图层 -->
      <el-amap-layer-satellite :visible="showLayer"></el-amap-layer-satellite>

      <el-amap-marker v-for="(item, index) in deviceMarker"
        :key="index"
        :position="item.position"
        :icon="item.icon"
        :offset="item.offset"
        @init="initMarker"
        @click="clickMarker($event, item)"
        :label="item.label">
      </el-amap-marker>
      <!-- :content="setIcon(item)" -->

      <el-amap-info-window :visible="infoWindow"
        :position="infoWinPosition"
        :offset="[25, -40]"
        :autoMove="true"
        :closeWhenClickMap="true"
        :showShadow="true"
        :isCustom="true">
        <div class="custom-info-window">
          <div class="angle"></div>
          <div style="position: absolute; top: 5px; right: 5px">
            <i class="el-icon-close icon-close"
              @click="infoWindow = false"></i>
          </div>
          <div style="padding: 10px 3px">
            <el-tabs :stretch="true"
              v-model="clickedDeviceDistinguish">
              <el-tab-pane :label="`传统有线   ${clickedMarkerData['传统有线'].length}个`"
                name="传统有线">
                <div class="info-window">
                  <div :class="[
                    'info-item',
                    deviceSource == data.deviceSource ? 'background' : '',
                  ]"
                    v-for="(data, index) in clickedMarkerData[
                      clickedDeviceDistinguish
                    ]"
                    :key="index"
                    @click="openDetail(data)">
                    <img :src="getDeviceDetailImg(data.deviceTypeName)"
                      alt=""
                      class="info-item-img" />
                    <span class="info-item-label">
                      {{ data.deviceName }}
                    </span>

                    <span class="info-item-state">
                      {{ data.deviceRunningState }}
                    </span>
                  </div>
                  <div style="text-align: center; margin-top: 20px"
                    v-if="clickedMarkerData['传统有线'].length == 0">
                    无设备。
                  </div>
                </div>
              </el-tab-pane>
              <el-tab-pane :label="`智能无线   ${clickedMarkerData['智能无线'].length}个`"
                name="智能无线">
                <div class="info-window">
                  <div :class="[
                    'info-item',
                    deviceSource == data.deviceSource ? 'background' : '',
                  ]"
                    v-for="(data, index) in clickedMarkerData[
                      clickedDeviceDistinguish
                    ]"
                    :key="index"
                    @click="openDetail(data)">
                    <img :src="getDeviceDetailImg(data.deviceTypeName)"
                      alt=""
                      class="info-item-img" />
                    <span class="info-item-label">
                      {{ data.deviceName }}
                    </span>

                    <span class="info-item-state">
                      {{ data.deviceRunningState }}
                    </span>
                  </div>
                  <div style="text-align: center; margin-top: 20px"
                    v-if="clickedMarkerData['智能无线'].length == 0">
                    无设备。
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>
      </el-amap-info-window>

      <!-- 缩放工具 -->
      <el-amap-control-tool-bar :visible="true"
        :position="{
          top: '0.8vh',
          left: '0.5vw',
          opacity: '0.8',
        }"
        @show="showControl"></el-amap-control-tool-bar>

      <!-- 地图类型 -->
      <div class="map-type">
        <div class="list"
          @mouseleave="onMouseLeaveCurrentMapType()"
          @mouseenter="onMouseEnterCurrentMapType()"
          v-if="isShowCurrentMapType">
          <div class="light">
            <img class="map-type-img"
              :src="mapTypeList[mapType - 1].selectedUrl" />
          </div>
        </div>
        <div class="select"
          v-if="!isShowCurrentMapType"
          @mouseleave="onMouseLeaveCurrentMapType()">
          <div class="light"
            style="flex: 1"
            v-for="item in mapTypeList"
            :key="item.id"
            @click="clickMapType(item)">
            <el-tooltip effect="dark"
              :content="item.title"
              placement="top-start">
              <img class="map-type-img"
                :src="mapType == item.id ? item.selectedUrl : item.url"
                :style="{
                  border: mapType == item.id ? '2px solid #3dbb99' : 'none',
                  'border-radius': mapType == item.id ? '2px' : '0px',
                }" />
            </el-tooltip>
          </div>
        </div>
      </div>

      <!-- 左边右下角图标 -->
      <div class="right-bottom-box">
        <div class="status-box"
          :class="showStatusBox ? 'status-box-bottom' : 'none'"
          @click="showStatusBox = !showStatusBox"
          :style="{
            background: deviceRunningStateObj.color
              ? deviceRunningStateObj.color
              : 'white',
          }">
          <img class="status-img"
            :src="require(`../../assets/index-map/state.png`)" />
          <span class="status-text">状态</span>
        </div>
        <div class="status-box-div"
          v-if="showStatusBox">
          <div class="status-box-item"
            :style="{
              background:
                state.value == deviceRunningState ? '#d4d3d3' : 'white',
            }"
            v-for="(state, index) in deviceRunningStateList"
            :key="index"
            @click="toSwitchState(state)">
            <img class="status-img"
              :src="require(`../../assets/index-map/${state.imgName}.png`)" />
            <span class="status-text">{{ state.label }}</span>
          </div>
        </div>

        <div class="type-box-div">
          <div class="type-box"
            :style="{
              background: deviceType == '' ? '#d4d3d3' : 'white',
            }"
            @click="toSwitchType('')">
            <img class="type-img"
              :src="require(`../../assets/index-map/device_all.png`)" />
            <span class="status-text">全部</span>
          </div>
          <div v-for="(type, index) in deviceTypeList"
            :key="index"
            class="type-box-item"
            :style="{
              background: deviceType == type.value ? '#d4d3d3' : 'white',
            }"
            @click="toSwitchType(type.value)">
            <img class="type-img"
              :src="require(`../../assets/index-map/${type.imgName}.png`)" />
            <span class="status-text">{{ type.label }}</span>
          </div>
        </div>
      </div>

      <!-- 预警统计 -->
      <early-warning-statistics
        :warningStatisticsData="warningStatisticsData"></early-warning-statistics>

      <!-- 设备详情 -->
      <div class="device-detail-box"
        v-if="detailWindow">
        <i class="el-icon-error close-icon"
          @click="closeDetail"></i>
        <div class="device-detail-header">
          <span v-if="getDeviceDetailImgBool(detailData.deviceTypeName)"
            style="color: white; margin: 0 5px 0 8px">
            <i class="iconfont icon-yangan"
              v-if="detailData.deviceTypeName == '烟感'"></i>
            <i class="iconfont icon-wengan"
              v-if="detailData.deviceTypeName == '温感'"></i>
            <i class="iconfont icon-tianranqi"
              v-if="detailData.deviceTypeName == '天然气'"></i>
            <i class="iconfont icon-shoudongbaojingqi1"
              v-if="detailData.deviceTypeName == '手报'"></i>

            <i class="iconfont icon-shuijin"
              v-if="detailData.deviceTypeName == '水浸报警'"></i>
            <i class="iconfont icon-hongwaitanceqi"
              v-if="detailData.deviceTypeName == '红外探测'"></i>
            <i class="iconfont icon-shengguangbaojingqi-"
              v-if="detailData.deviceTypeName == '声光报警'"></i>
          </span>
          <span v-else
            style="color: white; margin: 0 5px 0 8px">
            <i class="iconfont icon-qitashebei-1"></i>
          </span>
          <div style="display: flex; flex-direction: column">
            <span class="detail-card-title-text">{{ detailTitle }}</span>
            <span class="detail-card-title-text"
              style="font-size: 14px">{{
                deviceSource
              }}</span>
          </div>
        </div>
        <div class="device-detail-content">
          <el-tabs :stretch="true"
            v-model="detailActiveName">
            <el-tab-pane label="关联摄像机"
              name="first">
              <div style="height: 320px; padding-bottom: 10px">
                <iframe :src="detailData.streamUrl"
                  height="100%"
                  width="100%"
                  allowfullscreen
                  allow="autoplay; fullscreen; microphone;"></iframe>
              </div>
            </el-tab-pane>
            <el-tab-pane label="预警事件"
              name="second">
              <div class="early-warning-event"
                :style="{
                  'max-height': earlyWarningEventHight,
                  'min-height': '100px',
                }">
                <div class="event"
                  v-for="(item, index) in detailData.equipmentCollectAlertList"
                  :key="index"
                  :style="{
                    background: index % 2 == 0 ? '#fdfcfc' : '#eae7e7',
                  }">
                  <div class="event-item">
                    <span class="info-item-label">告警时间</span>
                    <span class="info-item-value">
                      {{ item.alertTimeStr }}
                    </span>
                  </div>

                  <div class="event-item">
                    <span class="info-item-label">告警地点</span>
                    <span class="info-item-value">
                      {{ item.deviceAddress }}
                    </span>
                  </div>
                  <div class="event-item">
                    <span class="info-item-label">告警原因</span>
                    <span class="info-item-value">
                      {{ item.alarmCause }}
                    </span>
                  </div>
                </div>
                <div v-if="
                  detailData.equipmentCollectAlertList &&
                  detailData.equipmentCollectAlertList.length == 0
                ">
                  <el-empty description="暂无数据"
                    :image-size="50"></el-empty>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="基本信息"
              name="third">
              <div class="info">
                <div class="info-item">
                  <span class="info-item-label">设备类型</span>
                  <span class="info-item-value">
                    {{ detailData.deviceTypeName }}
                  </span>
                </div>
                <div class="info-item">
                  <span class="info-item-label">设备编码</span>
                  <span class="info-item-value">
                    {{ detailData.deviceSource }}
                  </span>
                </div>
                <div class="info-item">
                  <span class="info-item-label">设备名称</span>
                  <span class="info-item-value">
                    {{ detailData.deviceName }}
                  </span>
                </div>

                <div class="info-item">
                  <span class="info-item-label">设备位置</span>
                  <span class="info-item-value">
                    {{ detailData.deviceLocation }}
                  </span>
                </div>
                <div class="info-item">
                  <span class="info-item-label">厂家</span>
                  <span class="info-item-value">
                    {{ detailData.manufactor }}
                  </span>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </el-amap>
  </div>
</template>

<script>
import mapApi from '@/api/gaode-map'
import EarlyWarningStatistics from './component/EarlyWarningStatistics.vue'
import { systemInfo } from '@/settings'
export default {
  name: 'Map',
  components: { EarlyWarningStatistics },
  data () {
    return {
      deviceType: '', // 设备类型(烟感:1；温感:2；手报:3；天然气:37；其他:-1)
      deviceTypeStr: '',
      deviceTypeList: [
        {
          label: '温感',
          value: 1,
          imgName: 'device_temperature_sensation',
        },
        {
          label: '烟感',
          value: 2,
          imgName: 'device_smoke_sensation',
        },

        {
          label: '手报',
          value: 3,
          imgName: 'device_hand_newspaper',
        },
        {
          label: '其他',
          value: -1,
          imgName: 'device_other',
        },
      ],
      deviceRunningState: '报警', // 设备运行状态(报警、故障、隔离、离线、反馈、启动、正常)
      deviceRunningStateList: [
        {
          label: '报警',
          value: '报警',
          color: '#F35A58',
          imgName: 'state_alarm',
        },
        {
          label: '故障',
          value: '故障',
          color: '#F48F57',
          imgName: 'state_fault',
        },
        {
          label: '隔离',
          value: '隔离',
          color: '#409EFF ',
          imgName: 'state_quarantine',
        },
        {
          label: '离线',
          value: '离线',
          color: '#F48F57 ',
          imgName: 'state_off_line',
        },
        {
          label: '反馈',
          value: '反馈',
          color: '#F48F57 ',
          imgName: 'state_feedback',
        },
        {
          label: '启动',
          value: '启动',
          color: '#F48F57 ',
          imgName: 'state_start_up',
        },
        {
          label: '正常',
          value: '正常',
          color: '#1DBB99 ',
          imgName: 'state_on_line',
        },
        {
          label: '全部',
          value: '',
          color: '#ffffff',
          imgName: 'state',
        },
      ],
      deviceRunningStateObj: {
        label: '报警',
        value: '报警',
        color: '#F35A58',
      },
      showStatusBox: false,

      map: null, //初始化地图
      center: systemInfo.name == '物联网实训平台' ? [108.30695, 23.133476] : [108.279271, 22.859303],
      zoom: 18,

      defaultMap: 'amap://styles/dark',
      showLayer: false,
      mapType: 3, // 默认卫星地图
      mapTypeList: [
        {
          url: require('@/assets/index-map/standard.png'),
          selectedUrl: require('@/assets/index-map/standard_selected.png'),
          title: '标准',
          id: 1,
          isDisplay: false,
        },
        {
          url: require('@/assets/index-map/real_scene.png'),
          selectedUrl: require('@/assets/index-map/real_scene_selected.png'),
          title: '实景',
          id: 2,
          isDisplay: true,
        },
        {
          url: require('@/assets/index-map/phantom_black.png'),
          selectedUrl: require('@/assets/index-map/phantom_black_selected.png'),
          title: '幻影黑',
          id: 3,
          isDisplay: false,
        },
      ],
      isShowCurrentMapType: true,

      warningStatisticsData: {}, //预警统计
      earlyWarningEventHight: 0,

      deviceDataList: [],
      deviceMarker: [],
      clickedMarkerData: { 传统有线: [], 智能无线: [] },
      deviceDetailImg: [
        {
          烟感: 'smoke_sensation',
        },
        {
          温感: 'temperature_sensation',
        },
        {
          天然气: 'natural_gas',
        },
        {
          手报: 'hand_newspaper',
        },
        {
          水浸报警: 'flooding_alarm',
        },
        {
          红外探测: 'infrared_acquisition',
        },
        {
          声光报警: 'audible_visual_alarm',
        },
      ],
      clickedDeviceDistinguish: '传统有线',
      // clickedMarkerData
      //     const wiredList = []
      // const wireless = []

      infoWindow: false, //聚点信息窗体
      infoWinPosition: [108.27947273101331, 22.85713439190149], //信息窗体位置

      detailData: {},
      detailWindow: false, //详情窗体
      deviceSource: '', //设备编码
      detailTitle: '',
      detailActiveName: 'second',

      timeId: null,
    }
  },
  beforeDestroy () {
    // clearInterval(this.timeId)
    // this.timeId = null
  },
  mounted () {
    this.timeId = setInterval(() => {
      this.getEquipmentCoordinate()
    }, 60 * 1000)
  },
  created () {
    this.earlyWarningEventHight = this.getHeightAndWidth()
    this.getEquipmentCoordinate()
  },
  methods: {
    getHeightAndWidth () {
      let clientHeight = 0
      if (
        document.body.scrollHeight === window.screen.height &&
        document.body.scrollWidth === window.screen.width
      ) {
        clientHeight = window.screen.height - 5 // 网页可见区域高
      } else {
        clientHeight = document.body.clientHeight - 5 // 网页可见区域高
      }
      console.log('clientHeight=', clientHeight - 450)
      return clientHeight - 450 + 'px'
    },

    getEquipmentCoordinate () {
      this.deviceMarker = []

      const data = {
        deviceType: this.deviceType,
        deviceRunningState: this.deviceRunningState,
      }
      mapApi.getEquipmentCoordinate(data).then((ret) => {
        this.warningStatisticsData = ret.data.data.count[0] // 今日预警统计
        this.deviceDataList = ret.data.data.list

        this.deviceDataList.forEach((ele) => {
          let trans = this.lnglat_cal(ele.longitude, ele.latitude)
          ele.longitude = trans.lng
          ele.latitude = trans.lat
        })

        this.getDeviceMarker()
      })
    },
    getDeviceMarker () {
      this.deviceMarker = []

      const list = []
      this.deviceDataList.forEach((ele) => {
        if (
          !list.find(
            (item) => item.lng == ele.longitude && item.lat == ele.latitude
          )
        ) {
          list.push({
            // deviceRunningState: this.deviceRunningState,
            lng: ele.longitude,
            lat: ele.latitude,
            data: [],
          })
        }
      })

      list.forEach((ele) => {
        const data = []
        this.deviceDataList.forEach((item) => {
          if (ele.lng == item.longitude && ele.lat == item.latitude) {
            data.push(item)
          }
        })

        data.sort((a, b) => {
          const arrSortStr = {
            报警: 0,
            故障: 1,
            隔离: 2,
            离线: 3,
            反馈: 4,
            启动: 5,
            正常: 6,
          }
          const idxA = arrSortStr[a.deviceRunningState]
          const idxB = arrSortStr[b.deviceRunningState]
          const result = idxA - idxB
          return result
        })

        ele.data = data
      })
      console.log('list=', list)

      list.forEach((ele) => {
        let imgStr = ''
        let imgPrefix = ''
        const stateList = []

        if (this.deviceType == '') {
          imgPrefix = 'device_all'
        } else {
          let name = ''
          this.deviceTypeList.forEach((item) => {
            if (item.value == this.deviceType) {
              name = item.imgName
            }
          })
          imgPrefix = name
        }

        ele.data.forEach((item) => {
          stateList.push(item.deviceRunningState)
        })

        let showState = ''
        if (stateList.indexOf('报警') > -1) {
          imgStr = imgPrefix + '_' + 'alarm'
          showState = '报警'
        } else if (stateList.indexOf('故障') > -1) {
          imgStr = imgPrefix + '_' + 'fault'
          showState = '故障'
        } else if (stateList.indexOf('隔离') > -1) {
          imgStr = imgPrefix + '_' + 'quarantine'
          showState = '隔离'
        } else if (stateList.indexOf('离线') > -1) {
          imgStr = imgPrefix + '_' + 'fault'
          showState = '离线'
        } else if (stateList.indexOf('反馈') > -1) {
          imgStr = imgPrefix + '_' + 'fault'
          showState = '反馈'
        } else if (stateList.indexOf('启动') > -1) {
          imgStr = imgPrefix + '_' + 'fault'
          showState = '启动'
        } else if (stateList.indexOf('正常') > -1) {
          imgStr = imgPrefix + '_' + 'on_line'
          showState = '正常'
        }

        if (this.mapType == 3) {
          imgStr = imgStr + '_' + this.mapType
        }
        let icon = require(`../../assets/index-map/${imgStr}.png`)
        if (showState != '正常' && showState != '隔离') {
          icon = require(`../../assets/index-map/${imgStr}.gif`)
        }

        this.deviceMarker.push({
          showState: showState,
          icon: icon,
          offset: new AMap.Pixel(-19, -56),
          position: [ele.lng, ele.lat],
          lng: ele.lng,
          lat: ele.lat,
          data: ele.data,
          title: ele.data.length,
          label: {
            content: ele.data.length,
            offset: [-38, -18],
          },
        })
      })
    },

    // 经纬度换算：百度-->高德
    lnglat_cal (lng, lat) {
      let x = lng - 0.0065,
        y = lat - 0.006,
        x_pi = (3.14159265358979324 * 3000.0) / 180.0

      let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi)
      let theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi)
      let tempLon = z * Math.cos(theta)
      let tempLat = z * Math.sin(theta)
      return { lng: tempLon, lat: tempLat }
    },

    // 初始化地图
    init (map) {
      map.setZooms([2, 19])
      this.map = map
    },
    // 监听地图层级变化
    changeZoom (zoom) {
      // let temp = this.map.getZoom()
      // if (temp < 19) {
      //   this.infoWindow = false
      // }
    },
    // 比例尺
    showControl () { },

    // 地图类型切换
    clickMapType (item) {
      this.mapType = item.id
      // this.showLayer = false
      switch (item.id) {
        case 1:
          this.showLayer = false
          this.defaultMap = 'amap://styles/normal'
          break
        case 2:
          this.defaultMap = 'amap://styles/dark'
          this.showLayer = true
          break
        case 3:
          this.showLayer = false
          this.defaultMap = 'amap://styles/dark'
          break
      }
      this.isShowCurrentMapType = true

      this.getDeviceMarker()
    },
    onMouseEnterCurrentMapType () {
      this.isShowCurrentMapType = false
    },
    onMouseLeaveCurrentMapType () {
      this.isShowCurrentMapType = true
    },

    toSwitchState (state) {
      this.deviceRunningState = state.value
      if (state.value == '') {
        this.deviceRunningStateObj = {}
      } else {
        this.deviceRunningStateObj = state
      }
      // if (this.deviceRunningState == state.value) {
      //   this.deviceRunningState = ''
      //   this.deviceRunningStateObj = {}
      // } else {
      //   this.deviceRunningState = state.value
      //   this.deviceRunningStateObj = state
      // }

      this.getEquipmentCoordinate()
    },

    toSwitchType (type) {
      this.deviceType = type
      if (type == '') {
        this.deviceTypeStr = ''
      } else {
        this.deviceTypeList.forEach((ele) => {
          if (ele.value == type) {
            this.deviceTypeStr = ele.label
          }
        })
      }

      this.getEquipmentCoordinate()
    },

    initMarker (marker) { },
    // 点击点标记打开信息窗体
    clickMarker (MapsEvent, marker) {
      console.log('MapsEvent=', MapsEvent)
      console.log('marker=', marker)

      this.clickedDeviceDistinguish = '传统有线'

      this.infoWinPosition = [
        MapsEvent.target._position[0],
        MapsEvent.target._position[1],
      ]

      //  const wiredList =  marker.data
      // const wireless =  marker.data
      // this.clickedMarkerData = marker.data
      const wiredList = []
      const wireless = []

      marker.data.forEach((ele) => {
        if (ele.deviceIsLine == 1) {
          wireless.push(ele)
        } else {
          wiredList.push(ele)
        }
      })
      this.clickedMarkerData = [
        {
          deviceIsLine: 1,
          list: wireless,
        },
        {
          deviceIsLine: 0,
          list: wiredList,
        },
      ]
      this.clickedMarkerData = {
        智能无线: wireless,
        传统有线: wiredList,
      }
      this.infoWindow = true
    },

    // 打开设备详情
    openDetail (item) {
      this.detailActiveName = 'second'
      this.deviceSource = item.deviceSource
      this.detailTitle = item.deviceName
      this.detailWindow = true
      this.getEquipmentDetail()
    },
    // 关闭详情窗口
    closeDetail () {
      this.detailWindow = false
    },
    getEquipmentDetail () {
      mapApi
        .equipmentMapDetail({
          deviceSource: this.deviceSource,
        })
        .then((res) => {
          if (res.status == 200) {
            this.detailData = res.data.data[0]

            this.clickedMarkerData[this.clickedDeviceDistinguish].forEach(
              (ele) => {
                if (ele.deviceSource == this.detailData.deviceSource) {
                  this.detailData.deviceLocation = ele.deviceLocation
                }
              }
            )
          }
        })
    },

    getImgSrc (imgName) {
      return require(`@/assets/home/${imgName}`)
    },
    getDeviceDetailImg (imgName) {
      let imgUrl = this.getImgSrc('other_device.png')
      this.deviceDetailImg.forEach((ele) => {
        for (const key in ele) {
          if (key == imgName) {
            imgUrl = this.getImgSrc(ele[imgName] + '.png')
          }
        }
      })
      return imgUrl
    },
    getDeviceDetailImgBool (imgName) {
      let bool = false
      this.deviceDetailImg.forEach((ele) => {
        for (const key in ele) {
          if (key == imgName) {
            bool = true
          }
        }
      })
      return bool
    },

    // 标记样式
    setIcon (item) {
      var content = document.createElement('img')
      content.src = item.icon
      if (
        item.showState == '报警' ||
        item.showState == '故障' ||
        item.showState == '离线' ||
        item.showState == '反馈' ||
        item.showState == '启动'
      ) {
        content.className = 'twinkle'
      } else {
        content.className = 'no-twinkle'
      }
      return content
    },
  },
}
</script>

<style lang="scss" scoped>
@import './style/map.scss';
</style>